<?php

namespace App\Command;

use App\Event\HangupCallEvent;
use App\Event\RechargeEvent;
use App\Event\UserChatEvent;
use App\Helpers\AppCache;
use App\Helpers\ConfigUtil;
use App\Helpers\Helper;
use App\Helpers\ImUtil;
use App\Helpers\PayUtil;
use App\Helpers\RedisUtil;
use App\Model\Act\InviteRewardLog;
use App\Model\HostPoolForNew;
use App\Model\Message;
use App\Model\PayOrder;
use App\Model\Service\ConsumeService;
use App\Model\TempCoupleApply;
use App\Model\TempCoupleMisc;
use App\Model\User;
use App\Model\UserRecValue;
use App\Model\VoiceCall;
use Carbon\Carbon;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\AsyncQueue\Driver\DriverInterface;
use Hyperf\Utils\Filesystem\Filesystem;
use Psr\EventDispatcher\EventDispatcherInterface;
use App\Helpers\QRcode;
use App\Helpers\SmsWelinkUtil;
use App\Model\Act\UserRankAct;
use App\Model\DailyTaskLog;
use App\Model\UserMsgLog;
use App\Model\UserProfile;
use App\Model\UserRecOnline;

/**
 * @Command
 */
class MyTestCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;


    /**
     * @var \Hyperf\Guzzle\ClientFactory
     */
    private $httpClient;


    /**
     * 消息队列
     * @var DriverInterface
     */
    protected $queueDriver;

    public function __construct(ContainerInterface $container, ClientFactory $clientFactory, DriverFactory $driverFactory)
    {
        $this->container = $container;
        $this->httpClient = $clientFactory;
        $this->queueDriver = $driverFactory->get('default');

        parent::__construct('mytest');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('run some test command');
    }

    protected function getArguments()
    {
        return [
            ['method', InputArgument::OPTIONAL, '方法', null],
            ['args', InputArgument::IS_ARRAY, '参数', null],
        ];
    }

    public function handle()
    {
        // Db::enableQueryLog();
        $method = $this->input->getArgument('method');
        $args = $this->input->getArgument('args');

        if (method_exists($this, $method)) {
            $begin = Carbon::now();
            $this->{$method}(...$args);
            $ms = Carbon::now()->diffInMilliseconds($begin);
            $this->info("processed $method in {$ms}ms");
        }
        // print_r(Db::getQueryLog());
        // echo PHP_EOL;
    }

    /**
     * 测试
     * php bin/hyperf.php mytest zpa 2
     */
    protected function zpa($param)
    {
        // $callRecord = VoiceCall::find($param);
        // $ret = ConsumeService::voiceCall($callRecord);
        // $this->info(json_encode($ret));
        // $ret = ImUtil::pushToAll('啦啦啦继续测试系统消息：2020-09-03', ImUtil::RONG_TEXT_TYPE, '新官方通知来了LaLaLa');
        // $ret = Message::sendSlient($param, 'CHANGE_FOR_NEW');
        // $ret = HostPoolForNew::getNotCallingHosts();
        // $ret = ConsumeService::doCoinUpdate(3, 4, 15.5, 6);
        // $users = User::where('im_account', '')->get();
        // foreach ($users as $user) {
        //     $ret = User::createRongIMAccount($user->id, $user->phone, '1');
        //     echo $ret . "\n";
        // }
        // $ret = Message::pushSystem($param, '华为推出鸿蒙2.0系统，想要超越谷歌与苹果？<a href="https://www.zhihu.com/zvideo/1289474861908299776">未来可期！</a>');

        // $ret = Message::pushSystem($param, '测试系统消息, 哈哈哈哈啦啦啦~');
        // $ret = InviteRewardLog::getRank();
        // $ret = array_column($ret, 'user_id');
        //充值事件触发
        // $ret = make(EventDispatcherInterface::class)->dispatch(new RechargeEvent($param, 58));
        // $params = explode('-', $param);
        // $ret = Message::sendSlient($params[0], 'CHAT_LIMIT', ['chat_user_id' => $params[1]]);
        // $ret = HostPoolForNew::getCoinSetting($param);
        // $ret = Message::sendSlient($param, 'CALL_OVER', ['new_free' => 1]);
        // UserRecValue::initNew();
        // UserRecValue::initHot();
        // UserRecValue::initOther();
        // var_dump($ret);
        // $value = 'https://www.jianshu.com/p/965c13ad6823';         //二维码内容
        // $errorCorrectionLevel = 'H';  //容错级别
        // $matrixPointSize = 6;      //生成图片大小
        // //生成二维码图片
        // $filename = 'xxx.png';
        // $ret = QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        // $ret = $this->actRank();
        // $userIds = explode('-', $param);
        // $ret = Message::sendSlient($userIds[0], 'CHAT_LIMIT', ['chat_user_id' => $userIds[1]]);
        // $ret = UserRecOnline::addRecord(88, [89, 90, 91, 92, 96, 100]);
        // $params = explode('-', $param);
        // $ret = DailyTaskLog::addLog($params[0], $params[1]);
        // $ret = UserMsgLog::getSendUserNum($param);
        //每日任务检测
        // make(EventDispatcherInterface::class)->dispatch(new RechargeEvent($params[0], $params[1]));
        // $ret = UserProfile::getOnlineUsers(UserProfile::ROLE_HOST, 10);
        // UserRecOnline::addRecUser($params[0], $params[1]);

        // $smsUtil = new SmsWelinkUtil();
        // $ret = $smsUtil->send('18902446236', '您的验证码是:123456');
        // $ret = Helper::sendCaptcha('18902446236', '666000');
        $ret = Message::pushSystem($event->userId, '刚刚发布的动态正在审核中, 审核结果稍后会告知你, 谢谢~');
        var_dump($ret);
    }

    /**
     * 添加在线推荐用户
     * php bin/hyperf.php mytest add_online_rec 93-66,82,86,90,92
     */
    function add_online_rec($param)
    {
        $params = explode('-', $param);
        $ret = UserRecOnline::addRecord($params[0], explode(',', $params[1]));
        var_dump($ret);
    }


    /**
     * 推送官方通知
     * php bin/hyperf.php mytest push_official 2
     */
    function push_official($param)
    {
        $ret = Message::pushOfficial($param == '0' ? [] : $param, [
            'title' => '新消息通知',
            'text' => '欢迎你注册极速蜜聊, 希望你在这里找到自己喜欢的声音',
            // 'pic' => 'http://imgcdn-aliyun.xiaoludd.com/9_1597149175_0.jpeg',
            // 'jump_info' => [
            //     'jump_link' => 'https://www.qq.com'
            // ]
        ], 'TEXT');
        var_dump($ret);
    }

    /**
     * 推送官方通知
     * php bin/hyperf.php mytest push_system 1
     */
    function push_system($param)
    {
        $ret = Message::pushSystem($param, '欢迎你注册极速蜜聊, 希望你在这里找到自己喜欢的声音<_>');
        var_dump($ret);
    }

    /**
     * 活动榜单
     */
    function actRank()
    {
        $start = null; //date('Y-m-d', strtotime('monday'));
        $rankInfo = [];
        $limitMax = ['chat' => 500, 'moment' => 300];
        //邀请充值 - 500
        $inviteInfo = UserRankAct::getInvitedRechargers($start);
        foreach ($inviteInfo as $profileId => $userIds) {
            if (!isset($rankInfo[$profileId])) $rankInfo[$profileId] = 0;
            $rankInfo[$profileId] += 500 * count($userIds);
        }

        //私信
        $userChats = UserRankAct::getHostChatRecords($start);
        foreach ($userChats as $userChat) {
            $hostId = $userChat->user_id;
            if (!isset($rankInfo[$hostId])) $rankInfo[$hostId] = 0;
            //发送一条私信 - 1
            $rankInfo[$hostId] += $userChat->msg_num * 1;
            //得到回复 - 50
            if ($userChat->chat_msg_num > 0) $rankInfo[$hostId] += 50;
        }

        //接听语音电话
        $voiceCalls = UserRankAct::getHostVoicecalls($start);
        foreach ($voiceCalls as $voiceCall) {
            $hostId = $voiceCall['chat_user_id'];
            if (!isset($rankInfo[$hostId])) $rankInfo[$hostId] = 0;
            //一分钟语聊内 - 50
            $voiceCall['call_time'] <= 60 && $rankInfo[$hostId] += 50;
            //两分钟以上 - 100
            $voiceCall['call_time'] > 60 && $rankInfo[$hostId] += 100;
        }

        //发布动态 - 50
        $moments = UserRankAct::getMoments($start);
        foreach ($moments as $moment) {
            $userId = $moment['user_id'];
            if (!isset($rankInfo[$userId])) $rankInfo[$userId] = 0;
            $rankInfo[$userId] += 50;
        }

        //入库
        krsort($rankInfo);
        $rank = 1;
        foreach ($rankInfo as $userId => $rankValue) {
            UserRankAct::addRecord($userId, $rankValue, $rank++, UserRankAct::ACT_HOST_RANK);
        }
    }

    function transferToAdminModel($param)
    {
        $adminPath = env('ROOT_DIR', '') . '/../voicecall-admin/app/Model';
        $models = env('ROOT_DIR', '') . '/app/Model';
        $fileSystem = new Filesystem();
        $modelFiles = $fileSystem->files($models, false);
        $finds = [
            'Hyperf\DbConnection\Model\Model' => 'Illuminate\Database\Eloquent\Model',
            'declare(strict_types=1);' => '',
            'Hyperf\DbConnection\Db' => 'Illuminate\Support\Facades\DB',
        ];
        foreach ($modelFiles as $modelFile) {
            $filename = $modelFile->getRelativePathname();
            $content = $modelFile->getContents();
            array_walk($finds, function ($replace, $find) use (&$content) {
                $content = str_replace($find, $replace, $content);
            });

            $adminModelFile = $adminPath . "/{$filename}";
            if (!$fileSystem->exists($adminModelFile)) {
                echo "$filename\n";
                $fileSystem->put($adminModelFile, $content);
            }
        }
    }

    /**
     * php bin/hyperf.php mytest exportCallmeData 100-31-35
     */
    function exportCallmeData($param)
    {
        $params = explode('-', $param);
        $startPage = intval($params[1]);
        $endPage = intval($params[2]);
        $pageSize = intval($params[0]);
        $url = "http://manage.51callme.com/MvcHome/MvcAction?_RegisterCode=AAEAAAD/////AQAAAAAAAAAGAQAAAGxjRE43Z2RrOVMzR1NzbUNjRVQ3cjlZSUVGVFlLd2JmbFp6aXdnNTQ0bUxCbzRrcHlFTDY2UHQ2b2N1VnJDZGtETWtiSkVOMGFkWGE1MXRFUWdvR1hVSEM3TlcvU2w3WTFpRjZTblBjeGJFUT0L&_AppID=113&_ControlName=GetUserDetailed&PageIndex=%s&PageSize=%s&BeginRechaMoney=%s&EndRechaMoney=%s&LiveType=-1";

        $file = 'callme.csv';
        // file_put_contents($file, '');
        for ($page = $startPage; $page <= $endPage; $page++) {
            $dataUrl = sprintf($url, $page, $pageSize, 0, 1000000);
            // echo $dataUrl . "\n";
            $data = Helper::httpReq($dataUrl, []);
            // file_put_contents('callme_data.json', $data);
            $data = json_decode($data, true);
            if (!$data['Data']['OnlyOneData']) {
                echo "第{$page}页没有充值数据\n";
                break;
            }
            $ctn = 0;
            foreach ($data['Data']['OnlyOneData'] as $item) {
                if (!$item['Phone']) continue;
                $str = "{$item['NickName']}\t{$item['Sex']}\t{$item['LiveName']}\t{$item['Phone']}\t{$item['TotalRecharge']}\n";
                file_put_contents($file, $str, FILE_APPEND);
                $ctn++;
            }
            echo "第{$page}页用户充值数据:{$ctn}\n";
        }
        return;
    }

    /**
     * php bin/hyperf.php mytest exportCallmeExpert 10-1
     */
    function exportCallmeExpert($param)
    {
        $params = explode('-', $param);
        $startPage = intval($params[1]);
        $endPage = intval($params[2]);
        $pageSize = intval($params[0]);
        // $url = "http://manage.51callme.com/MvcHome/MvcAction?_RegisterCode=AAEAAAD/////AQAAAAAAAAAGAQAAAGxjRE43Z2RrOVMzR1NzbUNjRVQ3cjlZSUVGVFlLd2JmbFp6aXdnNTQ0bUxCbzRrcHlFTDY2UHQ2b2N1VnJDZGtETWtiSkVOMGFkWGE1MXRFUWdvR1hVSEM3TlcvU2w3WTFpRjZTblBjeGJFUT0L&_AppID=113&_ControlName=GetExpertlList&PageIndex=%s&PageSize=%s&ServiceType=0";
        // $file = 'callme_expert.csv';

        $url = "http://manage.51callme.com/MvcHome/MvcAction?_RegisterCode=AAEAAAD/////AQAAAAAAAAAGAQAAAGxjRE43Z2RrOVMzR1NzbUNjRVQ3cjlZSUVGVFlLd2JmbFp6aXdnNTQ0bUxCbzRrcHlFTDY2UHQ2b2N1VnJDZGtETWtiSkVOMGFkWGE1MXRFUWdvR1hVSEM3TlcvU2w3WTFpRjZTblBjeGJFUT0L&_AppID=113&_ControlName=GetAngelList&PageIndex=%s&PageSize=%s";
        $file = 'callme_angel.csv';

        for ($page = $startPage; $page <= $endPage; $page++) {
            $dataUrl = sprintf($url, $page, $pageSize);
            // echo $dataUrl . "\n";
            $data = Helper::httpReq($dataUrl, []);
            // return file_put_contents('callme_data.json', $data);
            $data = json_decode($data, true);
            if (!$data['Data']['OnlyOneData']) {
                echo "第{$page}页没有专家数据\n";
                break;
            }
            $ctn = 0;
            foreach ($data['Data']['OnlyOneData'] as $item) {
                if (!$item['Phone']) continue;
                // $str = "{$item['Realname']}\t{$item['SexTitle']}\t{$item['Phone']}\t{$item['ServiceTypeName']}\t{$item['TotalIncomeMoney']}\t{$item['CurrentFee']}\n";
                $str = "{$item['NickName']}\t{$item['SexTitle']}\t{$item['LiveTypeName']}\t{$item['Phone']}\t{$item['AnswerMinute']}\t{$item['AnswerCount']}\n";
                file_put_contents($file, $str, FILE_APPEND);
                $ctn++;
            }
            echo "第{$page}页专家数据:{$ctn}\n";
        }
        return;
    }

    /**
     * php bin/hyperf.php mytest exportTianshi
     */
    function exportTianshi()
    {
        $file = '/Users/tonyzeng/Desktop/tian/tian-%s.txt';
        $fileResult = '/Users/tonyzeng/Desktop/tianshi.csv';
        $wages = [
            '2000以下', '2000-3000', '3000-4000', '4000-5000', '5000-8000', '8000-1w', '1w-2w', '2w-3w', '3w-4w', '4w-5w', '5w-10w', '10w以上'
        ];
        for ($i = 1; $i <= 15; $i++) {
            $f = sprintf($file, $i);
            $content = file_get_contents($f);
            $content = \json_decode($content, true);
            echo $f . "\n";
            foreach ($content['rows'] as $item) {
                $sex = $item['sex'] == 1 ? '男' : '女';
                $wage = $wages[$item['wages']];
                $str = "{$item['name']}\t{$item['phone']}\t{$sex}\t{$item['age']}\t{$item['occupation']}\t{$item['city']}\t{$wage}\t{$item['createTime']}\n";
                // echo $str;
                file_put_contents($fileResult, $str, FILE_APPEND);
            }
        }
    }


    function getMalePhone()
    {
        return Db::table('user_profile')->join('user', function ($join) {
            $where = [
                ['status', '=', User::STATUS_OK],
                ['gender', 1],
                ['phone', '<>', '']
            ];
            $join->on('user.id', '=', 'user_profile.user_id')->where($where)->whereRaw('locate("140000", phone)!=1');
        })->pluck('phone')->toArray();
    }
}
